import './FrontRouter.scss'


import { v4 } from 'uuid'
import { useState } from 'react'
import { Button, Tree, Popover, Input, Space, Popconfirm } from "antd"

import { PlusOutlined, SaveOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'

import { Encrypt } from '../../Utils/IndexedDB'
import { updateTreeByKey, removeTreeByKey } from '../../Utils/configFun'


const FrontRouter = ({ data, ModalEvent }) => {
    const [open, setOpen] = useState(false)
    const [Status, setStatus] = useState(false)
    const [NewMenu, setNewMenu] = useState('')
    const [treeData, setTreeData] = useState(data)
    const [EditUuid, setEditUuid] = useState()

    const onDrop = (info) => {
        const dropKey = info.node.key;
        const dragKey = info.dragNode.key;
        const dropPos = info.node.pos.split('-');
        const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
        const loop = (data, key, callback) => {
            for (let i = 0; i < data.length; i++) {
                if (data[i].key === key) return callback(data[i], i, data);
                if (data[i].children) loop(data[i].children, key, callback);
            }
        };
        const data = [...treeData];
        let dragObj;
        loop(data, dragKey, (item, index, arr) => {
            arr.splice(index, 1);
            dragObj = item;
        });
        if (!info.dropToGap) {
            loop(data, dropKey, (item) => {
                item.children = item.children || [];
                item.children.unshift(dragObj);
            });
        } else {
            let ar = [];
            let i;
            loop(data, dropKey, (_item, index, arr) => {
                ar = arr;
                i = index;
            });
            if (dropPosition === -1) ar.splice(i, 0, dragObj);
            else ar.splice(i + 1, 0, dragObj);
        }
        setTreeData(data);
    }

    const onAdd = () => {
        if (!!!NewMenu) {
            setStatus('error')
            return
        }
        const newRouter = { key: v4(), title: NewMenu }
        const data = [...treeData, newRouter]
        setTreeData(data)
        setNewMenu('')
        setOpen(false)
        setStatus(false)
    }

    const onSave = async () => {
        console.log('保存json文件', await Encrypt(treeData))
        ModalEvent.emit({ type: 'getRouter' })
    }

    const onModify = (key, value) => {
        if (!!!value) {
            setStatus('error')
            return
        }
        updateTreeByKey(treeData, key, value, 'key', 'title')
        setEditUuid(false)
        setNewMenu('')
        setStatus(false)
    }

    const onDelete = (key) => {
        const data = removeTreeByKey(treeData, key, 'key')
        setTreeData(data)
    }

    return (
        <div className='FrontRouter'>
            <Tree
                className='TreeMenu'
                draggable={{ icon: false }}
                blockNode
                selectable={false}
                defaultExpandAll
                onDrop={onDrop}
                treeData={treeData}
                titleRender={({ key, title }) => (
                    <div className='TreeItem' key={key}>
                        <div>{title}</div>
                        <div>
                            <Popover
                                placement="left"
                                open={EditUuid === key}
                                trigger="click"
                                onOpenChange={e => {
                                    if (e) setEditUuid(key)
                                    else setEditUuid(e)
                                }}
                                content={
                                    <Space.Compact style={{ width: 320 }}>
                                        <Input status={Status} placeholder='请输入新菜单名称' value={NewMenu} onChange={e => setNewMenu(e.target.value)} />
                                        <Button type="primary" onClick={() => onModify(key, NewMenu)}>修改</Button>
                                    </Space.Compact>
                                }
                            >
                                <EditOutlined />
                            </Popover>
                            <Popconfirm
                                title='删除提醒'
                                description="是否要删除当前菜单?"
                                onConfirm={() => onDelete(key)}
                                okText="删除"
                                cancelText="取消"
                            >
                                <DeleteOutlined style={{ color: '#f5222d' }} />
                            </Popconfirm>
                        </div>
                    </div>
                )}
            />
            <div className='Options'>
                <Popover
                    open={open}
                    trigger="click"
                    onOpenChange={setOpen}
                    content={
                        <Space.Compact style={{ width: 320 }}>
                            <Input status={Status} placeholder='请输入新菜单名称' value={NewMenu} onChange={e => setNewMenu(e.target.value)} />
                            <Button type="primary" onClick={onAdd}>添加</Button>
                        </Space.Compact>
                    }
                >
                    <Button type='primary' icon={<PlusOutlined />}>  新增 </Button>
                </Popover>
                <Button type='primary' icon={<SaveOutlined />} onClick={onSave}>  保存 </Button>
            </div>
        </div>
    )
}

export default FrontRouter